package com.db.logging;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class Logger {

    private Level loggerLevel = Level.DEBUG;
    private final String name;
    LoggerProcessor loggerProcessor;
    PrintWriter printWriter;
    static final int QUEUE_CAPACITY = 1024;
    DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT);

    BlockingQueue<String> queue = new LinkedBlockingQueue<String>(QUEUE_CAPACITY);

    public Logger(String name) throws FileNotFoundException {
        this.name = name;
        printWriter = new PrintWriter("logger.log");
        loggerProcessor = new LoggerProcessor();
        Thread t = new Thread(loggerProcessor);
        t.setDaemon(true);
        t.start();
    }

    public void debug(String msg) {
        log(Level.DEBUG, msg);
    }

    public void error(String msg) {
        log(Level.ERROR, msg);
    }

    public void info(String msg) {
        log(Level.INFO, msg);
    }

    public void log(Level level, String msg) {
        if (level.getLevel() < loggerLevel.getLevel())
            return;
        String message =
                String.format("%s %s [%s] %s", dateFormatter.format(new Date()), name, level, msg);
        queue.add(message);
    }

    public String getLoggerName() {
        return name;
    }

    private class LoggerProcessor implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    String message = queue.take();
                    printWriter.println(message);
                    printWriter.flush();
                } catch (InterruptedException e)
                {
                }
            }
        }
    }
}
